<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/8
 * Time: 14:23
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\UserBindModel;
use App\Http\Model\Mysql\UserModel;
use App\MultiTrait\PassportTrait;
use App\Utils\WechatUtil;
use Carbon\Carbon;
use App\Events\UserRegister;
use Illuminate\Support\Str;

class LoginService extends BaseService
{
    use PassportTrait;

    /**
     * 用户登录
     * @param string $js_code
     * @param string|null $user_unique
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function loginCheck(string $js_code, string $user_unique = NULL)
    {
        [$flag, $query_result]    =   WechatUtil::codeToSession($js_code);
        if (!$flag) {
            return [false, $query_result];
        }

        /**
         * 判断是否注册用户
         */
        $user_model    =   UserModel::where(['xcx_openid' => $query_result['openid']])->select(['uid', 'session_key', 'unionid', 'last_login_time', 'last_login_ip'])->first();
        if (!empty($user_model)) {
            /**
             * 保存session key
             */
            $user_model->session_key   =   $query_result['session_key'];
            $user_model->unionid       =   $query_result['unionid'] ?? '';
            $user_model->last_login_time=  Carbon::now()->timestamp;
            $user_model->last_login_ip =   request()->getClientIp();
            $user_model->save();
        } else {
            /**
             * 新用户注册
             */
            $user_model =   UserModel::create([
                'unique_id'     =>  createUniqueID(),
                'xcx_openid'    =>  $query_result['openid'],
                'session_key'   =>  $query_result['session_key'],
                'unionid'       =>  $query_result['unionid'] ?? '',
                'last_login_time'=> Carbon::now()->timestamp,
                'last_login_ip' =>  request()->getClientIp()
            ]);

            //触发用户注册事件
            event(new UserRegister($user_model));
        }

        /**
         * 绑定关系
         */
        if (!is_null($user_unique) && !empty($share_uid = UserModel::where(['unique_id' => $user_unique])->value('uid'))) {
            /**
             * 查询用户是否处于绑定状态
             */
            $bind_model  =   UserBindModel::where(['bind_user' => $user_model->uid])->orderBy('bind_time', 'desc')->first();
            if (empty($bind_model) || ($bind_model->bind_type == UserBindModel::BIND_WEAK && Carbon::now()->timestamp > $bind_model->expire_time)) {
                //如果未绑定 或者 处于弱绑定的关系的话且已过期，可以重新添加绑定关系
                $user_bind['share_user']    =   $share_uid;
                $user_bind['bind_user']     =   $user_model->uid;
                $user_bind['bind_type']     =   UserBindModel::BIND_WEAK;
                $user_bind['bind_time']     =   Carbon::now()->timestamp;
                $user_bind['expire_time']   =   Carbon::parse("+3 days")->timestamp;
                UserBindModel::create($user_bind);
            }
        }

        $login_result   =   $this->authenticate('api', [
            'grant_type'    =>  'password',
            'client_id'     =>  '3',
            'client_secret' =>  'bJpNb0nyUoZ0a10IoqPd27BOvWFgbd4mUghryDih',
            'username'      =>  $query_result['openid'],
            'password'      =>  $query_result['openid'],
            'scope'         =>  '',
            'guard_provider'=>  'users'
        ]);

        return [true, array_merge($login_result, $query_result)];
    }
}
